package cn.net.yugu.doraemon.dubbo.spi;

import cn.net.yugu.doraemon.dubbo.trace.TraceConstant;
import cn.net.yugu.doraemon.dubbo.trace.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;

/**
 * @description:
 * @author: wanghongli
 * @create: 2022-07-12 13:30:32
 */
@Slf4j
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class DubboTraceIdFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result;
        try {
            if (RpcContext.getContext().isConsumerSide()) {
                String traceId = TraceIdUtils.getTraceId();
                if (StringUtils.isBlank(traceId)) {
                    traceId = TraceIdUtils.generateTraceId();
                    TraceIdUtils.set(traceId);
                }
                RpcContext.getContext().setAttachment(TraceConstant.TRACE_ID, traceId);
            } else {
                String traceId = RpcContext.getContext().getAttachment(TraceConstant.TRACE_ID);
                if (StringUtils.isBlank(traceId)) {
                    traceId = TraceIdUtils.generateTraceId();
                }
                TraceIdUtils.set(traceId);
            }
            result = invoker.invoke(invocation);
        } finally {
            if (RpcContext.getContext().isProviderSide()) {
                TraceIdUtils.clear();
            }
        }
        return result;
    }
}
